import type { MessageType } from "./validate";
import regExpFn from './validate';

export type formType = 'text' | 'custom' | 'select' | 'textarea' | 'password' | 'date' | 'month' | 'datetimerange' | 'year' | 'number' | 'floatNum'

export type trigger = 'blur' | 'change'

// 需要通过失去焦点触发校验的类型
export let blurArrType = ['text','textarea','password','number','floatNum']

export interface selectForm { 
  label?: string,
  text?: string,
  value?: string
}

// 配置项的类型
export interface cols {
  label: string,
  prop: string,
  width: number,
  required?: boolean,
  max?: number,
  validate?: Function | string,
  type: formType,
  uploadRequired?: boolean,
  disabled?: boolean,
  multiple?: boolean,
  fn?: Function,
  select?: selectForm[],
  rows?: number,
  trigger?: trigger[],
  decimal?: number
}

// 显示时间数据的接受和传递的结构类型
export const forMat = (type:string) => {
  if(type == 'month'){ return 'YYYY-MM' };
  if(type == 'date'){ return 'YYYY-MM-DD' };
  if(type == 'year'){ return 'YYYY' };
  if(type == 'datetimerange'){ return 'YYYY-MM-DD' };
}

// 默认的校验规则
export const ergExtFunc = (val:MessageType, trigger?: trigger[]) =>{
  if (regExpFn[val]) {
    if(trigger && trigger.length){
      // 多个校验规则
      let arr:any = []
      trigger.forEach((v: trigger)=>{
        arr.push({
            trigger: v,
            validator: regExpFn[val],
        })
      })
      return arr;
    }else{
      return [
        {
          trigger: 'blur',
          validator: regExpFn[val],
        }
      ];
    }
  }
}

// 根据传进来的正则规则生成符合el-form的校验规则
export const regExpCustom = (val:any, trigger?: trigger[]) => {
  if(trigger && trigger.length){
    // 多个校验规则
    let arr:any = [];
    trigger.forEach((v: trigger)=>{
      arr.push({
        trigger: v,
        validator: regExpFn.validateCustom(val),
      })
    })
    return arr;
  }else{
    if(blurArrType.includes(val.type)){
      return [{
        trigger: 'blur',
        validator: regExpFn.validateCustom(val),
      }]
    }else{
      return [{
        trigger: 'change',
        validator: regExpFn.validateCustom(val),
      }]
    }
  }
}

// 动态计算label长度
export const computedLableWidth = (val: cols[]) =>{
  let arr = val.map((v:cols)=> { return v.label.length  })
  let maxLabel = Math.max(...arr);
  if(maxLabel > 7){ return maxLabel * 17.2 }else{ return 120 }
}